package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.TrafficHourCount;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_01_DwsTrafficHourCount extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_01_DwsTrafficHourCount().init(
                3002,
                1,
                "Dws_01_DwsTrafficHourCount",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //1.封装到一个pojo中
        SingleOutputStreamOperator<TrafficHourCount> beanStream = parseToPojo(stream);
        //2.开窗
        SingleOutputStreamOperator<TrafficHourCount> resultStream = windowAndAgg(beanStream);
        //3.写出到clickhouse中
        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHourCount> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_hour_count",TrafficHourCount.class));
    }

    private SingleOutputStreamOperator<TrafficHourCount> windowAndAgg(SingleOutputStreamOperator<TrafficHourCount> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficHourCount>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((bean,ts) -> bean.getTs())
                        .withIdleness(Duration.ofSeconds(1))
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TrafficHourCount>() {
                            @Override
                            public TrafficHourCount reduce(TrafficHourCount bean1,
                                                           TrafficHourCount bean2) throws Exception {
                                bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());
                                bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());
                                bean1.setSvCt(bean1.getSvCt() + bean2.getSvCt());
                                return bean1;
                            }
                        },
                        new ProcessAllWindowFunction<TrafficHourCount, TrafficHourCount, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<TrafficHourCount> elements,
                                                Collector<TrafficHourCount> out) throws Exception {
                                TrafficHourCount bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                if (bean.getSvCt() != 0) {
                                    //会话平均浏览页面数
                                    bean.setAvgTrafficPage(bean.getPvCt() / bean.getSvCt());

                                }
                                bean.setTs(System.currentTimeMillis());
                                out.collect(bean);

                            }
                        }

                );
    }

    private SingleOutputStreamOperator<TrafficHourCount> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficHourCount>() {
                    private ValueState<String> dateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState",String.class));
                    }

                    @Override
                    public TrafficHourCount map(JSONObject obj) throws Exception {
//                        if (obj==null){
//                            System.out.println("================");
//                        }
//                        System.out.println(obj+"================");
                        JSONObject common = obj.getJSONObject("common");

                        JSONObject page = obj.getJSONObject("page");
//                        if (page==null){
//                            System.out.println("-----------------");
//                        }
                        String isNew = common.getString("is_new");
                        String vc = common.getString("vc");
                        String sc = common.getString("sc");
                        String ar = common.getString("ar");
                        Long ts = obj.getLong("ts");


                        //页面浏览数
                        Long pvCt = 1l;

                        //会话数
                        Long svCt = 0l;
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            svCt = 1l;
                        }
                        //独立访客数
                        Long uvCt = 0l;
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)){
                            dateState.update(today);
                            uvCt = 1l;
                        }
                        return new TrafficHourCount("","",vc,
                                sc,ar,isNew,
                                uvCt,pvCt,svCt,
                                0l,ts);
                    }
                });
    }
}
